import { uploadFile } from "@/server/common/file.js";
import mobileDetect from "mobile-detect"; //具体哪个页面用到单独引用
import QRCode from "qrcode";
import { showNotify } from "vant";
import VConsole from "vconsole";
import { ref } from "vue";
import wx from "weixin-js-sdk";
import { useUsersStore } from "../stores/user";
import { removeToken } from "./auth";

// 清空用户信息、token
export const clearUserInfo = () => {
  removeToken();
  useUsersStore().$patch({
    name: "",
    avatar: "",
    roles: "",
    permissions: "",
    userInfo: ""
  });
};

// 获取href地址参数
export function getUrlQuery() {
  const queryString = location.href.split("?")[1];
  let obj = {};
  if (!queryString) return obj;
  const list = queryString.replace(/&amp;/g, "&").split("&");
  list.forEach((item) => {
    let [key, value] = item.split("=");
    obj[key] = value;
  });
  return obj;
}

// 采集来源 存放调研问卷数据采集的对象来源 wechat：微信公众号；weapp：微信小程序；h5：H5轻应用；
export function getSource() {
  var ua = navigator.userAgent.toLowerCase();
  if (ua.match(/MicroMessenger/i) == "micromessenger") {
    // 小程序中
    return new Promise((resolve) => {
      wx.miniProgram.getEnv(function (res) {
        if (res.miniprogram) resolve("weapp");
        else resolve("wechat");
      });
    });
  } else {
    return new Promise((resolve) => {
      resolve("h5");
    });
  }
}

// 获取设备参数
export const getDeviceInfo = () => {
  let browser = getBrowserInfo();
  let deviceType = navigator.userAgent; //获取userAgent信息
  let md = new mobileDetect(navigator.userAgent); //初始化mobile-detect
  let os = md.os(); // 终端操作系统版本
  let model = ""; // 终端设备类型
  let browseType = browser.browser + " " + browser.ver; // 浏览器类型及版本信息
  if (os === "iOS") {
    //ios系统的处理
    os = md.os() + md.version("iPhone");
    model = md.mobile();
  } else if (os === "AndroidOS") {
    //Android系
    os = md.os() + md.version("Android");
    const sss = deviceType.split(";");
    let str = sss.filter((ss) => ss.includes("Build/"))[0] || "Build/";
    model = str.substring(0, str.indexOf("Build/"));
  }
  return { os, model, browseType };
};

// 浏览器以及浏览器版本
export function getBrowserInfo() {
  const Sys = {};
  const ua = navigator.userAgent.toLowerCase();
  const re = /(msie|firefox|chrome|opera|version|mozilla).*?([\d.]+)/;
  const m = ua.match(re);
  Sys.browser = m[1].replace(/version/, "'safari");
  Sys.ver = m[2];
  return Sys;
}

// 数组日期格式化 list = ['2020', '02', '21'] format = ['年', '月', '日']
export const arrDateFormat = (list, format) => {
  let mat = format || ["年", "月", "日"];
  let arr = (list || []).map((item, index) => {
    return item + mat[index];
  });
  return arr.join("");
};

/**
 * 格式化函数 ， 给日期格式化
 * date为 new Date()对象， fmt为 'yyyy-MM-dd hh:mm:ss'的格式
 */
export function formatDate(date, fmt) {
  date = date || new Date();
  fmt = fmt || "yyyy-MM-dd";
  //获取年份
  if (/(y+)/.test(fmt)) {
    let dateY = date.getFullYear() + ""; // 把数字变成字符串
    fmt = fmt.replace(RegExp.$1, dateY.substr(4 - RegExp.$1.length)); //RegExp.$1 在判断中出现过，且是括号括起来的，所以 RegExp.$1 就是 "yyyy"
  }
  //获取其他
  let o = {
    "M+": date.getMonth() + 1,
    "d+": date.getDate(),
    "h+": date.getHours(),
    "m+": date.getMinutes(),
    "s+": date.getSeconds()
  };
  for (const k in o) {
    if (new RegExp(`(${k})`).test(fmt)) {
      let str = o[k] + "";
      fmt = fmt.replace(
        RegExp.$1,
        RegExp.$1.length === 1 ? str : str.padStart(2, "0")
      );
    }
  }
  return fmt;
}

// 是否手机端
export function isMobile() {
  const type = getUrlQuery()?.type; // href获取数据
  if (type === "h5" || type === "pc") {
    return type === "h5"; // 优先输出 路由带参数的情况
  } else {
    let userAgentInfo = navigator.userAgent;
    let Agents = [
      "Android",
      "iPhone",
      "SymbianOS",
      "Windows Phone",
      "iPad",
      "iPod"
    ];
    let getArr = Agents.filter((i) => userAgentInfo.includes(i));
    return !!getArr.length;
  }
}

// 网页跳转
export function jumpWeb(url, type = "_blank") {
  if (url.includes("http:") || url.includes("https:")) {
    window.open(url, type);
  } else {
    window.open(`http://${url}`, type);
  }
}

// 问卷标题 是否展示序号
export function titleText(options, item) {
  return options.showOrderNum
    ? item.orderNum + "、" + item.itemTitle
    : item.itemTitle;
}

// 微信页面跳转 type: navigateTo  switchTab  reLaunch  redirectTo
export const wxPageRedirect = (page, type = "navigateTo") => {
  console.log(page, type);
  wx.miniProgram[type]({
    url: page,
    success: function (res) {
      console.log(res);
    },
    fail: function (error) {
      showNotify({ type: "danger", message: error });
    },
    complete: function (msg) {
      console.log(msg);
    }
  });
};
// 向小程序发送消息
export const dispatchToWechat = (msg) => {
  wx.miniProgram.postMessage({ data: msg });
};
// 跳转微信登录
export const goWxLogin = () => {
  wxPageRedirect(
    "../authLoginNew/authLoginNew?url=" +
    encodeURIComponent(location.href + "&token=#token#")
  );
};
// 提出文本 html 标签
export const removeHTMLTag = (str) => {
  str = str.replace(/<\/?[^>]*>/g, ""); //去除HTML tag
  str = str.replace(/[ | ]*\n/g, "\n"); //去除行尾空白
  return str;
};
// 输入框粘贴操作
export const insertTextNodeForPaste = (event) => {
  let items = event.clipboardData && event.clipboardData.items;
  const selection = window.getSelection();
  let pasteTxt = (event.clipboardData || window.clipboardData).getData("text");
  selection.deleteFromDocument();
  if (items && items.length) {
    let filterItem = items;
    // 检索剪切板items
    for (let i = 0; i < filterItem.length; i++) {
      if (filterItem[i].type.indexOf("image") !== -1) {
        // 图片暂时不支持
        // let file = filterItem[i].getAsFile();
        // let blob = new Blob([file], { type: 'image/png' || 'application/*' });
        // let fragment = selection.getRangeAt(0).createContextualFragment(`<img src=${URL.createObjectURL(blob)} />`);
        // selection.getRangeAt(0).insertNode(fragment.lastChild);
      } else {
        if (["text/plain"].includes(filterItem[i].type)) {
          selection.getRangeAt(0).insertNode(document.createTextNode(pasteTxt));
        }
      }
    }
  }
};

// HTML标签转译  "&lt;p&gt;&lt;/p&gt;&lt;img /&gt;"
export const htmlToStr = (html) => {
  html = html.replace(/&lt;/g, "&lt`;").replace(/&gt;/g, "&gt`;");
  html = html.replace(/</g, "&lt;").replace(/>/g, "&gt;");
  return html;
};

// 转译成html
export const strToHtml = (str) => {
  if (!str) return str;
  str = str.replace(/&lt;/g, "<").replace(/&gt;/g, ">");
  str = str.replace(/&lt`;/g, "&lt;").replace(/&gt`;/g, "&gt;");
  return str;
};
// base64转文件流
export const dataURLtoBlob = (url) => {
  let arr = url.split(","),
    mime = arr[0].match(/:(.*?);/)[1],
    baseStr = atob(arr[1]),
    n = baseStr.length,
    u8arr = new Uint8Array(n);
  while (n--) {
    u8arr[n] = baseStr.charCodeAt(n);
  }
  return new Blob([u8arr], {
    type: mime
  });
};
// 分享 生成二维码
export const share = (url) => {
  let opts = { errorCorrectionLevel: "H", type: "image/jpeg" };
  let wechatUrl =
    "https://lsapp.szzgh.org:90/image/zg-test/?url=" + encodeURIComponent(url);
  QRCode.toDataURL(wechatUrl, opts, function (err, baseUrl) {
    if (err) throw err;
    let file = dataURLtoBlob(baseUrl);
    let fileName = new Date().getTime() + ".jpeg";
    let newFile = new window.File([file], fileName, { type: file.type }); // 这里的files是你接收的file
    let formDate = new FormData();
    formDate.append("file", newFile);
    uploadFile(formDate).then(async (res) => {
      let url = res.data.url;
      if (url.substr(-4) !== "jpeg") url += "jpeg";
      let sourceType = await getSource();
      if (sourceType === "weapp") {
        wxPageRedirect("../downImg/downImg?url=" + url);
      } else {
        jumpWeb(url);
      }
    });
  });
};
// 显示showVConsole
const clickI = ref(0);
const clickTimer = ref();
export const showVConsole = () => {
  if (clickI.value > 6) {
    new VConsole();
    clearTimeout(clickTimer.value);
  }
  clickI.value++;
  clearTimeout(clickTimer.value);
  clickTimer.value = setTimeout(() => {
    clickI.value = 0;
  }, 300);
};
